﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

using STSdb.MTL.Utils.Serialization;

namespace STSdb.MTL
{
    public class EngineTransactionsLog:IDisposable
    {

        public enum eTransactionOperationType
        {
            INSERT,
            UPDATE,
            UPDATE_KEY,
            DELETE,
            COMMIT
        }


        public class TransactionOperation
        {
            public TransactionOperation()
            {
                TransactionOperationType = eTransactionOperationType.INSERT;
            }

            public eTransactionOperationType TransactionOperationType { get; set; }

            public string TableName { get; set; }            
            public int ManagedThreadId { get; set; }

            private string _keyType = String.Empty;
            public string KeyType 
            {
                get { return this._keyType; }
            }

            private string _valueType = String.Empty;
            public string ValueType
            {
                get { return this._valueType; }
            }

            private object _key = null;
            public object Key 
            { 
                get {return this._key;} 
                set {
                    this._key = value;
                    this._keyType = this._key.GetType().ToString();
                } 
            }

            private object _value = null;
            public object Value
            {
                get { return this._value; }
                set
                {
                    this._value = value;
                    this._valueType = this._value.GetType().ToString();
                }
            }
        }


        private EngineTransactionsLogSetup _setup = null;

        FileStream _currentLogFile = null;

        public EngineTransactionsLog(EngineTransactionsLogSetup setup)
        {
            this._setup = setup;

            _currentLogFile = File.Open(this._setup.LogFilesFolderName + Path.DirectorySeparatorChar + this._setup.LogFileBaseName, FileMode.Append, FileAccess.Write, FileShare.Read);
        }

        public void Log(TransactionOperation transactionOperation)
        {
            string serCommand = transactionOperation.SerializeXml();
            byte[] bs = System.Text.Encoding.UTF8.GetBytes(serCommand);

            this._currentLogFile.Write(bs,0,bs.Length);
            this._currentLogFile.Flush();
        }

        /// <summary>
        /// Don't Forget To Dispose it, when engine disposes
        /// </summary>
        public void Dispose()
        {
            this._currentLogFile.Close();
        }
    }
}
